<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="股票代码" prop="stockCode">
        <el-input
            v-model="queryParams.stockCode"
            placeholder="请输入股票代码"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易方向" prop="direction">
        <el-select v-model="queryParams.direction" placeholder="请选择交易方向" clearable style="width: 240px">
          <el-option
              v-for="dict in trade_direction"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="交易来源" prop="source">-->
      <!--        <el-select v-model="queryParams.source" placeholder="请选择交易来源" clearable style="width: 240px">-->
      <!--          <el-option-->
      <!--              v-for="dict in task_source"-->
      <!--              :key="dict.value"-->
      <!--              :label="dict.label"-->
      <!--              :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="证券账号" prop="accountNo">
        <el-select
            v-model="queryParams.accountNo"
            placeholder="请选择证券账号"
            clearable
            style="width: 240px"
        >
          <el-option
              v-for="item in accountOptions"
              :key="item.accountNo"
              :label="item.accountName"
              :value="item.accountNo"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="交易阶段" prop="phase">-->
      <!--        <el-select v-model="queryParams.phase" placeholder="请选择交易阶段" clearable style="width: 240px">-->
      <!--          <el-option-->
      <!--              v-for="dict in order_status"-->
      <!--              :key="dict.value"-->
      <!--              :label="dict.label"-->
      <!--              :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="交易状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择交易状态" clearable style="width: 240px">
          <el-option
              v-for="dict in trade_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['stock:trade:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['stock:trade:edit']"
        >修改
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" row-key="id" :data="tradeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="交易来源" align="center" prop="source">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :options="task_source" :value="scope.row.source"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="股票代码" align="center" prop="stockCode"/>
      <el-table-column label="股票名称" align="center" prop="stockName"/>
      <el-table-column label="交易方向" align="center" prop="direction">
        <template #default="scope">
          <dict-tag :options="trade_direction" :value="scope.row.direction"/>
        </template>
      </el-table-column>
      <el-table-column label="交易价" align="center" prop="price">
        <template #default="scope">
          {{ formatCurrency(scope.row.price) }}
        </template>
      </el-table-column>
      <el-table-column label="交易股数" align="center" prop="quantity"/>
      <el-table-column label="交易账户" align="center" prop="accountNo">
        <template #default="scope">
          {{ getAccountName(scope.row.accountNo) }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="交易阶段" align="center" prop="phase">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :options="order_status" :value="scope.row.phase"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="交易状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="trade_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="220">
        <template #default="scope">
          <el-button link
                     v-if="scope.row.status === '1'"
                     type="primary"
                     icon="Edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['stock:trade:edit']">
            修改
          </el-button>
          <el-button link
                     v-if="scope.row.status === '1'"
                     type="primary"
                     icon="VideoPlay"
                     @click="handleStatus('2', scope.row.id)"
                     v-hasPermi="['stock:trade:edit']">
            启动
          </el-button>
          <el-button link
                     v-if="scope.row.status === '1'"
                     type="primary"
                     icon="Delete"
                     @click="handleStatus('0', scope.row.id)"
                     v-hasPermi="['stock:trade:edit']">
            删除
          </el-button>
          <el-button link
                     v-if="scope.row.status === '2'"
                     type="primary"
                     icon="VideoPause"
                     @click="handleStatus('1', scope.row.id)"
                     v-hasPermi="['stock:trade:edit']">
            停止
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改股票交易任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" height="500px" append-to-body>
      <el-form ref="tradeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="证券账户" prop="accountNo">
          <el-select v-model="form.accountNo" placeholder="请选择证券账户">
            <el-option
                v-for="item in accountOptions"
                :key="item.accountNo"
                :label="item.accountName"
                :value="item.accountNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="股票代码" prop="stockCode">
          <el-input v-model="form.stockCode" placeholder="必填，如：600519 或 600519.SH"/>
        </el-form-item>
        <el-form-item label="交易方向" prop="direction">
          <el-radio-group v-model="form.direction">
            <el-radio
                v-for="dict in trade_direction"
                :key="dict.value"
                :value="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="交易价" prop="price">
          <el-input v-model="form.price" placeholder="请输入交易价"/>
        </el-form-item>
        <el-form-item label="交易股数" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入交易股数"/>
        </el-form-item>
        <el-form-item label="交易状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="1">停止</el-radio>
            <el-radio value="2">启动</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {addTrade, getTrade, listTrade, updateTrade, updateTradeStatus} from "@/api/stock/trade";
import {checkStockExists} from "@/api/stock/info";
import {validateCurrency, validateStockQuantity} from "@/utils/validate";
import {formatCurrency} from "@/utils/format";
import {listAccount} from "@/api/stock/account";

const {proxy} = getCurrentInstance();
const {
  trade_direction,
  trade_status,
  task_source,
  order_status
} = proxy.useDict('trade_direction', 'trade_status', 'task_source', 'order_status');

const tradeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const accountOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stockCode: null,
    direction: null,
    source: null,
    accountNo: null,
    phase: null,
    status: null,
  },
  rules: {
    accountNo: [
      {required: true, message: "交易账户不能为空", trigger: "change"}
    ],
    stockCode: [
      {required: true, message: "股票代码不能为空", trigger: "blur"}
    ],
    direction: [
      {required: true, message: "交易方向不能为空", trigger: "change"}
    ],
    price: [
      {required: true, message: "交易价不能为空", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (!validateCurrency(value)) {
            callback(new Error('请输入正确的货币格式'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    quantity: [
      {required: true, message: "交易股数不能为空", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (!validateStockQuantity(value)) {
            callback(new Error('交易股数必须为正整数且是100的倍数'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    status: [
      {required: true, message: "交易状态不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询股票交易任务列表 */
function getList() {
  loading.value = true;
  listTrade(queryParams.value).then(response => {
    tradeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    stockCode: null,
    direction: "1",
    price: null,
    quantity: null,
    source: "1",
    accountNo: null,
    status: "1",
    phase: 48,
  };
  proxy.resetForm("tradeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加股票交易任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getTrade(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改股票交易任务";
  });
}

/** 处理状态变更 */
function handleStatus(status, id) {
  const statusText = status === '0' ? '删除' : status === '1' ? '停止' : '启动';
  proxy.$modal.confirm(`是否确认${statusText}任务?`).then(() => {
    return updateTradeStatus({
      id: id,
      status: status
    });
  }).then(() => {
    proxy.$modal.msgSuccess(`${statusText}成功`);
    getList();
  }).catch(() => {
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tradeRef"].validate(valid => {
    if (valid) {
      // 先检查股票代码是否存在
      checkStockExists(form.value.stockCode).then(res => {
        if (res.code === 200) {
          if (form.value.id != null) {
            updateTrade(form.value).then(response => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
          } else {
            addTrade(form.value).then(response => {
              proxy.$modal.msgSuccess("新增成功");
              open.value = false;
              getList();
            });
          }
        }
      }).catch(() => {
      });
    }
  });
}

/** 根据账户号码获取账户名称 */
function getAccountName(accountNo) {
  if (!accountNo) return '';
  const account = accountOptions.value.find(item => item.accountNo === accountNo);
  return account ? account.accountName : accountNo;
}

/** 查询账户列表 */
function getAccountList() {
  listAccount({}).then(response => {
    accountOptions.value = response.rows;
  });
}

Promise.all([getList(), getAccountList()]);
</script>